package com.kun.config;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.kun.handler.datapermission.DefaultDataPermissionHandler;
import com.kun.handler.tenant.DefaultTenantLineHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Map;
import java.util.Set;

/**
 * @author kun.li
 */
public class MybatisPlusConfig {

    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 是否开启支持多租户
     */
    @Value("${mybatis-plus.configuration.enableTenant:true}")
    private boolean enableTenant;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 数据权限
        DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor(new DefaultDataPermissionHandler());
        // 多租户支持
        if (enableTenant) {
            TenantLineInnerInterceptor tenantLineInterceptor = new TenantLineInnerInterceptor(getDefaultTenantLineHandler());
            mybatisPlusInterceptor.addInnerInterceptor(tenantLineInterceptor);
        }
        mybatisPlusInterceptor.addInnerInterceptor(dataPermissionInterceptor);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        return mybatisPlusInterceptor;
    }

    private DefaultTenantLineHandler getDefaultTenantLineHandler() {
        Map<String, DefaultTenantLineHandler> beansOfType = applicationContext.getBeansOfType(DefaultTenantLineHandler.class);
        if (MapUtil.isNotEmpty(beansOfType)) {
            return beansOfType.get(DefaultTenantLineHandler.class.getName());
        }
        DefaultTenantLineHandler defaultTenantLineHandler = new DefaultTenantLineHandler();
        defaultTenantLineHandler.setBackPackage(Set.of("com.kun"));
        defaultTenantLineHandler.init();
        return defaultTenantLineHandler;

    }

    /**
     * 自动填充属性
     *
     * @return
     */
    @Bean
    public DefaultMetaObjectHandler defaultMetaObjectHandler() {
        return new DefaultMetaObjectHandler();
    }


}
